package com.ibeetl.cms.web;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.rbac.UserLoginInfo;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.cms.entity.AlipayUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 第三方登录
 */
@Controller
@Slf4j
public class ThreeLoginController {

    private static final String MODEL = "/cms/aliLogin";
    @Value("${ali.URL}")
    private String URL;
    @Value("${ali.APP_ID}")
    private String APP_ID;
    @Value("${ali.APP_PRIVATE_KEY}")
    private String APP_PRIVATE_KEY;
    @Value("${ali.FORMAT}")
    private String FORMAT;
    @Value("${ali.CHARSET}")
    private String CHARSET;
    @Value("${ali.ALIPAY_PUBLIC_KEY}")
    private String ALIPAY_PUBLIC_KEY;
    @Value("${ali.SIGN_TYPE}")
    private String SIGN_TYPE;

    @Autowired
    private CoreUserService userService;

    @Autowired
    private CorePlatformService platformService;

    @Autowired
    private AlipayClient alipayClient;

    @GetMapping(MODEL + "/login.do")
    public ModelAndView  aliLogin() {
        ModelAndView view = new ModelAndView("/threeLogin.html") ;
        // https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=商户的APPID&scope=auth_user&redirect_uri=ENCODED_URL
        String aliStr="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id="+APP_ID+"&scope=auth_user&redirect_uri="+"http%3a%2f%2fb2944625b9.zicp.vip%2fcms%2faliLogin%2freturnAddress.do";
        view.addObject("aliStr",aliStr);
        return view;
    }

    @GetMapping(MODEL + "/returnAddress.do")
    public String  returnAddress(@RequestParam(name = "auth_code")String authCode, @RequestParam(name = "app_id")String appId, @RequestParam(name = "scope")String scope) {
        log.info("回调成功！");
        // 模拟admin登录
        UserLoginInfo info = userService.login("admin", "123456");
        if (info == null) {
            throw new PlatformException("用户名密码错");
        }
        CoreUser user = info.getUser();
        CoreOrg currentOrg = info.getOrgs().get(0);
        for (CoreOrg org : info.getOrgs()) {
            if (org.getId() == user.getOrgId()) {
                currentOrg = org;
                break;
            }
        }
        info.setCurrentOrg(currentOrg);
        // 记录登录信息到session
        this.platformService.setLoginUser(info.getUser(), info.getCurrentOrg(), info.getOrgs());

        // 测试  auth_code获取用户的user_id和access_token
        String accessToken = getAccessToken(authCode);
        if(accessToken != null) {
            AlipayUser aUser = getUserInfoByToken(accessToken);
            log.info("AlipayUser message: {}", aUser);
        }
        return "redirect:/index.do";
    }

    /**
     * 根据auth_code获取用户的user_id和access_token
     * @param authCode
     * @return
     */
    public String getAccessToken(String authCode) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            return oauthTokenResponse.getAccessToken();
        } catch (Exception e) {

            log.error("使用authCode获取信息失败！", e);
            return null;
        }
    }

    /**
     * 根据access_token获取用户信息
     * @param token
     * @return
     */
    public AlipayUser getUserInfoByToken(String token) {
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest ();
        try {
            AlipayUserInfoShareResponse response =  alipayClient.execute(request, token);
            if (response.isSuccess()) {
                //打印响应信息
//                System.out.println(ReflectionToStringBuilder.toString(response));
                //封装支付宝对象信息
                AlipayUser alipayUser = new AlipayUser();
                alipayUser.setAddress(response.getAddress());
                alipayUser.setCertNo(response.getCertNo());
                alipayUser.setCity(response.getCity());
                alipayUser.setCollegeName(response.getCollegeName());
                alipayUser.setDegree(response.getDegree());
                alipayUser.setMobile(response.getMobile());
                alipayUser.setPhone(response.getPhone());
                alipayUser.setProvince(response.getProvince());
                alipayUser.setUserName(response.getUserName());
                alipayUser.setNickName(response.getNickName());
                return alipayUser;
            }
            log.error("根据 access_token获取用户信息失败!");
            return null;

        } catch (Exception e) {
            log.error("根据 access_token获取用户信息抛出异常！", e);
            return null;
        }
    }
}


